from flask import Flask,jsonify,request,Blueprint,session,send_from_directory
from common.res import (getRes,getErrorRes,getSuccessRes,getDataRes)
from common.sqlInjectionSecurity import sqlEscape,sqlEscapeField
import os
import random
from controller.public_param import MODEL_DOWN_DIR,MODEL_UPLOAD_DIR

down_file = Blueprint('down_file',__name__)

@down_file.route("/file/down_file/<path:filename>",methods=['GET', 'POST'])
def download_file(filename):
    try:
        return send_from_directory(MODEL_DOWN_DIR, filename, as_attachment=True)
    except:
        return '<h1>该文件不存在或无法下载</h1>'


@down_file.route("/file/up_file/<path:filename>",methods=['POST'])
def upload_file(filename):
    file = request.files.get('file')
    random_integer = str(random.randint(1, 10000))
    if file:
        url =os.path.join(MODEL_UPLOAD_DIR,random_integer+filename)
        file.save(url)
        res = getSuccessRes(data=random_integer)
    else:
        res = getErrorRes(data=0)
    return jsonify(res)